from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_breadcrumb(category):
    """获取面包屑导航"""

    breadcrumb = {
        'category_1': '',
        'category_2': '',
        'category_3': '',
    }

    # 如果没有上级id的，就是一级分类
    if category.parent is None:
        breadcrumb['category_1'] = category
    # 如果下一级中数量为0的，就是三级分类
    elif category.subs.count() == 0:
        breadcrumb['category_3'] = category
        breadcrumb['category_2'] = category.parent
        breadcrumb['category_1'] = category.parent.parent

    else:
        breadcrumb['category_2'] = category
        breadcrumb['category_1'] = category.parent

    return breadcrumb


def create_categories():
    """商品分类，商品类别"""
    # 暂时使用到的页面有 index.html,list.html
    categories_dict = OrderedDict()
    # 查询数据库(商品频道)
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        # 当前频道id
        group_id = channel.group_id
        # 如果频道没有在这个字典中
        if group_id not in categories_dict:
            categories_dict[group_id] = {'channels': [], 'sub_cats': []}

        category_1 = channel.category  # 当前频道中的所有类别 即一级分类

        # 将一级分类添加到字典中
        categories_dict[group_id]['channels'].append({
            'id': category_1.id,
            'name': category_1.name,
            'url': channel.url
        })
        for category_2 in category_1.subs.all():
            category2_dict = {
                'id': category_2.id,
                'name': category_2.name,
                'sub_cats': []
            }
            for category_3 in category_2.subs.all():
                category3_dict = {
                    'id': category_3.id,
                    'name': category_3.name,
                }
                category2_dict['sub_cats'].append(category3_dict)
            categories_dict[group_id]['sub_cats'].append(category2_dict)

    return categories_dict
